/*
 * 
 * 
 * 
 */
package com.cms.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cms.Feedback;
import com.cms.entity.Category;
import com.cms.entity.Content;
import com.cms.entity.ModelField;
import com.cms.entity.PushContent;
import com.cms.entity.Site;
import com.cms.routes.RouteMapping;
import com.cms.util.HttpUtils;
import com.cms.util.SystemUtils;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import org.apache.commons.lang.ArrayUtils;

import java.util.*;


/**
 * Controller - 内容
 * 
 * 
 * 
 */
@RouteMapping(url = "/admin/content")

public class ContentController extends BaseController {

	/**
	 * 添加
	 */
	public void add() {
		Long categoryId = getParaToLong("categoryId");
		Category category = new Category().dao().findById(categoryId);
		if(category.getModelId() != null){
		    List<ModelField> modelFields = new ModelField().dao().findList(category.getModelId(),true,getCurrentSite().getId());
		    setAttr("modelFields", modelFields);
		}else{
		    setAttr("modelFields", new ArrayList<ModelField>());
		}
		setAttr("category", category);
		Map<Integer,String> selfTypes = SystemUtils.getSelfTypes(getCurrentSite().getId());
		setAttr("selfTypes", selfTypes);
		render(getView("content/add"));
	}
	
	/**
	 * 保存
	 */
	public void save() {
		Long categoryId = getParaToLong("categoryId");
		if (categoryId == 50) {
			PushContent content = getModel(PushContent.class, "", true);
			Long modelId = content.getCategory().getModelId();
			List<ModelField> modelFields = new ModelField().dao().findList(modelId, true, getCurrentSite().getId());
			Map<String, Object> model = new HashMap<String, Object>();
			for (ModelField modelField : modelFields) {
				if ("multipleFile".equals(modelField.getType())) {
					model.put(modelField.getName(), getParaValues(modelField.getName()));
				} else {
					model.put(modelField.getName(), getPara(modelField.getName()));
				}
			}
			content.setSiteId(getCurrentSite().getId());
			content.setCreateDate(new Date());
			content.setModifyDate(new Date());
			content.setModelFieldValue("");
			content.save();
			redirect(getListQuery("/admin/content/data?categoryId=" + content.getCategoryId()));
		}else {
			Content content = getModel(Content.class, "", true);
			Long modelId = content.getCategory().getModelId();
			List<ModelField> modelFields = new ModelField().dao().findList(modelId, true, getCurrentSite().getId());
			Map<String, Object> model = new HashMap<String, Object>();
			for (ModelField modelField : modelFields) {
				if ("multipleFile".equals(modelField.getType())) {
					model.put(modelField.getName(), getParaValues(modelField.getName()));
				} else {
					model.put(modelField.getName(), getPara(modelField.getName()));
				}
			}
			content.setSiteId(getCurrentSite().getId());

			content.setCreateDate(new Date());
			content.setModifyDate(new Date());
			//content.setModelFieldValue(JSONObject.toJSONString(model));
			content.setModelFieldValue("");
			content.save();
			redirect(getListQuery("/admin/content/data?categoryId=" + content.getCategoryId()));
		}

	}

    /**
     * 保存并提交到省级
     */
    public void saveAndCommit() {
        Content content = getModel(Content.class,"",true);
        Long modelId = content.getCategory().getModelId();
        List<ModelField> modelFields = new ModelField().dao().findList(modelId,true,getCurrentSite().getId());
        Map<String,Object> model = new HashMap<String,Object>();
        for(ModelField modelField : modelFields){
            if("multipleFile".equals(modelField.getType())){
                model.put(modelField.getName(), getParaValues(modelField.getName()));
            }else{
                model.put(modelField.getName(), getPara(modelField.getName()));
            }
        }
        content.setSiteId(getCurrentSite().getId());
        content.setCreateDate(new Date());
        content.setModifyDate(new Date());
        content.setModelFieldValue(JSONObject.toJSONString(model));
        Prop p = PropKit.use("config.properties");
        String province = p.get("province.get");
        String provincePost = p.get("province.post");
        String errorPage = p.get("error.page");
        System.out.println("提交省本级的接口："+provincePost);
        String cmsContent=JSONObject.toJSONString(content);
        Map<String ,String > queryParams = new HashMap<>();
        queryParams.put("cmsContent",cmsContent);
        try {
            List<Site> sites = new Site().dao().findList(Site.NEW_TYPE);
            String whichCity="未填写";
            if(null!=sites && !sites.isEmpty()) {

                Site site=sites.get(0);
                whichCity=site.getName();
            }
            Integer result= HttpUtils.fun5(provincePost,cmsContent,whichCity);
            //保存成功
            if(result==200) {
                content.save();
                redirect(getListQuery("/admin/content/data?categoryId="+content.getCategoryId()));
            }
            //保存失败
            else {
                //redirect(getListQuery("/admin/content/data?categoryId="+content.getCategoryId()));
                redirect(errorPage);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            redirect(errorPage);
        }
        //请求省级提交结束
    }



	/**
	 * 编辑
	 */
	public void edit() {
		Long id = getParaToLong("id");
		
		/*判断编辑推送信息*/
		Long categoryId = getParaToLong("categoryId");
		if(categoryId==50){
			PushContent content = new PushContent().dao().findById(id);
			Category category = new Category().dao().findById(content.getCategoryId());
			if(category.getModelId() != null){
	            List<ModelField> modelFields = new ModelField().dao().findList(category.getModelId(),true,getCurrentSite().getId());
	            setAttr("modelFields", modelFields);
	        }else{
	            setAttr("modelFields", new ArrayList<ModelField>());
	        }
			
			setAttr("content", content);
			Map<Integer,String> selfTypes = SystemUtils.getSelfTypes(getCurrentSite().getId());
	        setAttr("selfTypes", selfTypes);
			render(getView("content/edit"));
		}else{
			Content content = new Content().dao().findById(id);
			Category category = new Category().dao().findById(content.getCategoryId());
			if(category.getModelId() != null){
	            List<ModelField> modelFields = new ModelField().dao().findList(category.getModelId(),true,getCurrentSite().getId());
	            setAttr("modelFields", modelFields);
	        }else{
	            setAttr("modelFields", new ArrayList<ModelField>());
	        }
			setAttr("content", content);
			Map<Integer,String> selfTypes = SystemUtils.getSelfTypes(getCurrentSite().getId());
	        setAttr("selfTypes", selfTypes);
			render(getView("content/edit"));
		}
		
		
	}

	/**
	 * 更新
	 */
	public void update() {
		
		Long categoryId = getParaToLong("categoryId");
		
		if(categoryId==50){
			PushContent content = getModel(PushContent.class,"",true);  
			Long modelId = content.getCategory().getModelId();
			List<ModelField> modelFields = new ModelField().dao().findList(modelId,true,getCurrentSite().getId());
			Map<String,Object> model = new HashMap<String,Object>();
			for(ModelField modelField : modelFields){
			    if("multipleFile".equals(modelField.getType())){
			        model.put(modelField.getName(), getParaValues(modelField.getName()));
			    }else{
			        model.put(modelField.getName(), getPara(modelField.getName()));
			    }
			}
			content.setModelFieldValue(JSONObject.toJSONString(model));
			content.setModifyDate(new Date());
			content.update();
			redirect(getListQuery("/admin/content/data?categoryId="+content.getCategoryId()));
		}else{
			Content content = getModel(Content.class,"",true);  
			Long modelId = content.getCategory().getModelId();
			List<ModelField> modelFields = new ModelField().dao().findList(modelId,true,getCurrentSite().getId());
			Map<String,Object> model = new HashMap<String,Object>();
			for(ModelField modelField : modelFields){
			    if("multipleFile".equals(modelField.getType())){
			        model.put(modelField.getName(), getParaValues(modelField.getName()));
			    }else{
			        model.put(modelField.getName(), getPara(modelField.getName()));
			    }
			}
			content.setModelFieldValue(JSONObject.toJSONString(model));
			content.setModifyDate(new Date());
			content.update();
			redirect(getListQuery("/admin/content/data?categoryId="+content.getCategoryId()));
		}
		
		
	}
	
   /**
     * 修改排序
     */
    public void updateSort(){
        String sortArray = getPara("sortArray");
        JSONArray jsonArray = JSONArray.parseArray(sortArray);
        for(int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Long id = jsonObject.getLong("id");
            Integer sort = jsonObject.getInteger("sort");
            Content content = new Content().dao().findById(id);
            content.setSort(sort);
            content.update();
        }
        renderJson(Feedback.success(new HashMap<>()));
    }
    
    /**
     * 修改推送信息排序
     */
    public void updateSortPushContent(){
        String sortArray = getPara("sortArray");
        JSONArray jsonArray = JSONArray.parseArray(sortArray);
        for(int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Long id = jsonObject.getLong("id");
            Integer sort = jsonObject.getInteger("sort");
            PushContent content = new PushContent().dao().findById(id);
            content.setSort(sort);
            content.update();
        }
        renderJson(Feedback.success(new HashMap<>()));
    }
	
	
	/**
	 * 列表
	 */
	public void list(){
	    setAttr("categoryTree", new Category().dao().findTree(getCurrentSite().getId()));
	    render(getView("content/list"));
	}

	/**
	 * 数据
	 */
	public void data() {
	    String title = getPara("title");
		Long categoryId = getParaToLong("categoryId");
		Integer pageNumber = getParaToInt("pageNumber");
		Integer type = getParaToInt("type");
		Integer status = getParaToInt("status");
		if(pageNumber==null){
			pageNumber = 1;
		}
		setAttr("categoryId",categoryId);
		/*判断是否查询推送信息表*/
		if(categoryId==50){
		 Page<PushContent> page = new PushContent().dao().findPage(status,categoryId,type,title,pageNumber,PAGE_SIZE,getCurrentSite().getId());
		 setAttr("page",page);
		}else{
			setAttr("page", new Content().dao().findPage(categoryId,type,title,pageNumber,PAGE_SIZE,getCurrentSite().getId()));
		}
		
		setAttr("title", title);
		setAttr("type", type);
		setAttr("status", status);
		Map<Integer,String> selfTypes = SystemUtils.getSelfTypes(getCurrentSite().getId());
		Map<Integer,String> check = SystemUtils.getCheck(getCurrentSite().getId());
        setAttr("selfTypes", selfTypes);
        setAttr("checks", check);
		render(getView("content/data"));
	}

	/**
	 * 删除
	 */
	public void delete() {
		Long ids[] = getParaValuesToLong("ids");
		
		if(ArrayUtils.isNotEmpty(ids)){
			for(Long id:ids){
				new Content().dao().deleteById(id);
			}
		}
		renderJson(Feedback.success(new HashMap<>()));
	}
	
	/**
	 * 删除推送信息
	 */
	public void deletePushContent() {
		Long ids[] = getParaValuesToLong("ids");
		
		if(ArrayUtils.isNotEmpty(ids)){
			for(Long id:ids){
				new PushContent().dao().deleteById(id);
			}
		}
		renderJson(Feedback.success(new HashMap<>()));
	}

	/**
	 * 修改审核状态
	 */
	public void checkPushContent(){
		Long ids[] = getParaValuesToLong("ids");
		if(ArrayUtils.isNotEmpty(ids)){
			for(Long id:ids){
				PushContent pushContent = new PushContent().dao().findById(id);
				pushContent.setIsCheck(1);
				pushContent.update();
			}
		}
		renderJson(Feedback.success(new HashMap<>()));
	}

}